﻿// -------------------- iSharePoint -------------------- //
// 
//  Company:	IT Complex, LLC
//  Project:	Smart.Common
//  File name:	SPEventReceiversExts.cs
//  Developer:	Igor Solomatov
//  Created:	05.03.2013
// 
// -------------------- iSharePoint -------------------- //

using System;
using System.Collections.Generic;
using Microsoft.SharePoint;

namespace Smart.Common
{
	public static class SPEventReceiversExts
	{
		public static void RemoveEventReceivers(this SPList list, Type eventReceiverType, params  SPEventReceiverType[] eventTypes)
		{
			var assemblyQualifiedName = eventReceiverType.Assembly.FullName;
			var className = eventReceiverType.FullName;
			var eventReceivers = new List<SPEventReceiverDefinition>();

			foreach (SPEventReceiverDefinition definition in list.EventReceivers)
			{
				if (definition.Assembly != assemblyQualifiedName && definition.Class != className && !definition.Type.In(eventTypes))
					continue;

				eventReceivers.Add(definition);
			}

			foreach (var receiverDefinition in eventReceivers)
			{
				receiverDefinition.Delete();
			}
		}

		public static void AddEventReceiver(this SPList list, Type eventReceiverType, SPEventReceiverType eventType, int sequenceNumber, SPEventReceiverSynchronization synchronization)
		{
			var eventReceiverDefinition = list.EventReceivers.Add();

			eventReceiverDefinition.Assembly = eventReceiverType.Assembly.FullName;
			eventReceiverDefinition.Class = eventReceiverType.FullName;
			eventReceiverDefinition.Type = eventType;
			eventReceiverDefinition.SequenceNumber = sequenceNumber;
			eventReceiverDefinition.Synchronization = synchronization;

			try
			{
				eventReceiverDefinition.Update();
			}
			catch (Exception ex)
			{
				H.LX("SPEventReceiversExts.AddEventReceiver", ex);
			}
		}

		public static void EnsureEventReceiverSynchronous(this SPList list, Type eventReceiverType, params SPEventReceiverType[] eventTypes)
		{
			var assemblyQualifiedName = eventReceiverType.Assembly.FullName;
			var className = eventReceiverType.FullName;
			var eventReceivers = new List<SPEventReceiverDefinition>();

			foreach (SPEventReceiverDefinition definition in list.EventReceivers)
			{
				if (definition.Assembly != assemblyQualifiedName && definition.Class != className && definition.Synchronization != SPEventReceiverSynchronization.Asynchronous && !definition.Type.In(eventTypes))
					continue;

				eventReceivers.Add(definition);
			}

			foreach (var definition in eventReceivers)
				try
				{
					definition.Synchronization = SPEventReceiverSynchronization.Synchronous;

					definition.Update();
				}
				catch (Exception ex)
				{
					H.LX("SPEventReceiversExts.EnsureEventReceiverSynchronous", ex);
				}
		}
	}
}